<template>
  <div>
    <div v-if="loading" class="loading">
      加载组件详情中...
    </div>
    <div v-else-if="!component" class="error">
      未找到组件信息，请返回首页重新选择组件。
      <router-link to="/" class="btn">返回首页</router-link>
    </div>
    <div v-else class="component-detail">
      <h1>
        {{ component.name }}
        <span class="badge vue-version">Vue {{ component.vueVersion }}</span>
      </h1>
      <p v-if="component.description">{{ component.description }}</p>
      
      <div class="info-grid">
        <div class="info-item">
          <strong>文件路径</strong>
          <span>{{ component.filePath }}</span>
        </div>
        <div class="info-item">
          <strong>最后更新</strong>
          <span>{{ formatDate(component.updatedAt) }}</span>
        </div>
      </div>
      
      <!-- Props部分 -->
      <div v-if="component.props && component.props.length > 0" class="section">
        <h2>Props</h2>
        <table>
          <thead>
            <tr>
              <th>名称</th>
              <th>类型</th>
              <th>默认值</th>
              <th>必填</th>
              <th>描述</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="prop in component.props" :key="prop.name">
              <td><code>{{ prop.name }}</code></td>
              <td><code>{{ prop.type }}</code></td>
              <td>{{ prop.defaultValue !== undefined ? prop.defaultValue : '-' }}</td>
              <td>{{ prop.required ? '是' : '否' }}</td>
              <td>{{ prop.description || '-' }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- Events部分 -->
      <div v-if="component.events && component.events.length > 0" class="section">
        <h2>Events</h2>
        <div class="event-item" v-for="event in component.events" :key="event.name">
          <h3><code>{{ event.name }}</code></h3>
          <p v-if="event.description">{{ event.description }}</p>
          
          <table v-if="event.arguments && event.arguments.length > 0">
            <thead>
              <tr>
                <th>参数</th>
                <th>类型</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="arg in event.arguments" :key="arg.name">
                <td><code>{{ arg.name }}</code></td>
                <td><code>{{ arg.type }}</code></td>
                <td>{{ arg.description || '-' }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- Slots部分 -->
      <div v-if="component.slots && component.slots.length > 0" class="section">
        <h2>Slots</h2>
        <div class="slot-item" v-for="slot in component.slots" :key="slot.name">
          <h3><code>{{ slot.name || 'default' }}</code></h3>
          <p v-if="slot.description">{{ slot.description }}</p>
          
          <table v-if="slot.bindings && slot.bindings.length > 0">
            <thead>
              <tr>
                <th>绑定名</th>
                <th>类型</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="binding in slot.bindings" :key="binding.name">
                <td><code>{{ binding.name }}</code></td>
                <td><code>{{ binding.type }}</code></td>
                <td>{{ binding.description || '-' }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- Methods部分 -->
      <div v-if="component.methods && component.methods.length > 0" class="section">
        <h2>Methods</h2>
        <div class="method-item" v-for="method in component.methods" :key="method.name">
          <h3><code>{{ method.name }}({{ formatParams(method.params) }})</code></h3>
          <p v-if="method.description">{{ method.description }}</p>
          
          <table v-if="method.params && method.params.length > 0">
            <thead>
              <tr>
                <th>参数</th>
                <th>类型</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="param in method.params" :key="param.name">
                <td><code>{{ param.name }}</code></td>
                <td><code>{{ param.type }}</code></td>
                <td>{{ param.description || '-' }}</td>
              </tr>
            </tbody>
          </table>
          
          <div v-if="method.returns">
            <strong>返回: </strong>
            <code>{{ method.returns.type }}</code>
            <span v-if="method.returns.description"> - {{ method.returns.description }}</span>
          </div>
        </div>
      </div>
      
      <router-link to="/" class="btn">返回首页</router-link>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

interface ComponentProp {
  name: string;
  type: string;
  description: string;
  defaultValue?: string;
  required: boolean;
  values?: string[];
}

interface ComponentEventArgument {
  name: string;
  type: string;
  description: string;
}

interface ComponentEvent {
  name: string;
  description: string;
  arguments: ComponentEventArgument[];
}

interface ComponentSlotBinding {
  name: string;
  type: string;
  description: string;
}

interface ComponentSlot {
  name: string;
  description: string;
  bindings: ComponentSlotBinding[];
}

interface ComponentMethodParam {
  name: string;
  type: string;
  description: string;
}

interface ComponentMethodReturn {
  type: string;
  description: string;
}

interface ComponentMethod {
  name: string;
  description: string;
  params: ComponentMethodParam[];
  returns?: ComponentMethodReturn;
}

interface Component {
  id: string;
  encodedId: string;
  name: string;
  description: string;
  filePath: string;
  props: ComponentProp[];
  events: ComponentEvent[];
  slots: ComponentSlot[];
  methods: ComponentMethod[];
  createdAt: string;
  updatedAt: string;
  vueVersion: string;
}

export default defineComponent({
  name: 'ComponentDetail',
  props: {
    encodedId: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const loading = ref(true);
    const component = ref<Component | null>(null);
    const router = useRouter();
    const webSocket = ref<WebSocket | null>(null);

    // 连接WebSocket
    const connectWebSocket = () => {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      webSocket.value = new WebSocket(`${protocol}//${window.location.host}/ws`);
      
      webSocket.value.onopen = () => {
        console.log('WebSocket连接已建立');
      };
      
      webSocket.value.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'components-updated') {
            // 当收到组件更新消息时，重新加载组件
            fetchComponentDetail();
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
        }
      };
      
      webSocket.value.onclose = () => {
        console.log('WebSocket连接已关闭');
        // 尝试重新连接
        setTimeout(connectWebSocket, 5000);
      };
      
      webSocket.value.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
    };

    // 获取组件详情
    const fetchComponentDetail = async () => {
      try {
        loading.value = true;
        const response = await fetch(`/api/component/${props.encodedId}`);
        
        if (!response.ok) {
          if (response.status === 404) {
            component.value = null;
            return;
          }
          throw new Error(`HTTP错误: ${response.status}`);
        }
        
        const data = await response.json();
        component.value = data;
      } catch (error) {
        console.error('获取组件详情失败:', error);
        component.value = null;
      } finally {
        loading.value = false;
      }
    };

    // 格式化日期
    const formatDate = (dateStr: string) => {
      try {
        const date = new Date(dateStr);
        return date.toLocaleString();
      } catch (e) {
        return dateStr;
      }
    };

    // 格式化方法参数
    const formatParams = (params: ComponentMethodParam[]) => {
      if (!params || !params.length) return '';
      return params.map(param => param.name).join(', ');
    };

    onMounted(async () => {
      await fetchComponentDetail();
      connectWebSocket();
    });

    return {
      loading,
      component,
      formatDate,
      formatParams
    };
  }
});
</script>

<style lang="scss" scoped>
.error {
  text-align: center;
  padding: 40px 20px;
  color: #f56c6c;
  
  .btn {
    display: inline-block;
    margin-top: 16px;
    padding: 8px 16px;
    background-color: var(--color-primary);
    color: white;
    border-radius: 4px;
    text-decoration: none;
  }
}

.slot-item,
.method-item {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--color-border);
  
  h3 {
    font-size: 18px;
    margin-bottom: 8px;
    color: var(--color-secondary);
  }
}

.component-detail {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}
</style> 